<?php

namespace Data;

class Verify extends Base {

	const VERIFY_CODE_KEY = 'verify_code_key_';
	const APP_VERIFY_CODE_KEY = 'app_verify_code_key_';

    /**
     * 浏览器用户一分钟发送验证码倒计时.
     */
    const SEND_VERIFY_TTL = 'send_verify_ttl';

    /**
     * 短信验证码
     */
    const MESSAGE_CODE_KEY = 'message_code_key';

    /**
     * 浏览器用户一天发送多少次验证码.
     */
    const SEND_VERIFY_DAY_TIME = 'send_verify_day_time';

	public function setVerify($userMask, $val) {
		$key = self::VERIFY_CODE_KEY . $userMask;
		$this->getRedis()->setex($key, 60, $val);
	}

	public function getVerify($userMask) {
		$key = self::VERIFY_CODE_KEY . $userMask;
		return $this->getRedis()->get($key);
	}

	public function appSetVerify($userMask, $val) {
		$key = self::APP_VERIFY_CODE_KEY . $userMask;
		$this->getRedis()->setex($key, 180, $val);
	}

	public function appGetVerify($userMask) {
		$key = self::APP_VERIFY_CODE_KEY . $userMask;
		return $this->getRedis()->get($key);
	}

    /**
     * 得到一个用户发送验证码的倒计时，记录这个用户一天发过多少次验证码.
     *
     * @param string $key
     * @param string $type
     *
     * @return array
     */
    public function getSendVerifyNumber($key, $type) {
        $redis = $this->getRedis();
        $ttl = (int) $redis->ttl(self::SEND_VERIFY_TTL . $type . $key);
        $ttl = $ttl > 0 ? $ttl : 0;
        $dayNumber = $redis->get(self::SEND_VERIFY_DAY_TIME . $type . $key);
        $data = array(
            'ttl' => (int) $ttl,
            'dayNumber' => (int) $dayNumber,
        );
        return $data;
    }

    /**
     * 设置一个用户发送验证码的倒计时，记录这个用户一天发过多少次验证码.
     *
     * @param string $key
     * @param string $type
     *
     * @return void
     */
    public function incSendVerifyNumber($key, $type) {
        $redis = $this->getRedis();
        // 60秒只能发一次的倒计时
        $redis->setex(self::SEND_VERIFY_TTL . $type . $key, 60, 1);
        // 记录每天发了多少次
        $redis->incr(self::SEND_VERIFY_DAY_TIME . $type . $key);
        $redis->expire(self::SEND_VERIFY_DAY_TIME . $type . $key, 86400);
    }

    public function setMessageCode($mask, $phone, $code) {
        $redis = $this->getRedis();
        $key = self::MESSAGE_CODE_KEY . md5($mask . $phone);
        $redis->setex($key, 600, $code);
    }

    public function getMessageCode($mask, $phone) {
        $redis = $this->getRedis();
        $key = self::MESSAGE_CODE_KEY . md5($mask . $phone);
        return $redis->get($key);
    }
}